library clipboard_util;

import 'package:clipboard_util/src/util/log/log.dart';
import 'package:flutter/cupertino.dart';
import 'package:async/async.dart';
import 'package:flutter/services.dart';

import 'src/util/clipboard/clipboard_manager.dart';

class ClipboardUtil with WidgetsBindingObserver{

  ClipboardUtil._internal();
  static final ClipboardUtil _instance = ClipboardUtil._internal();
  // static ClipboardUtil get instance => _instance;

  static late ClipboardManager _clipboardManager;

  static bool _hasInit = false;
  static bool _hasChanged = false;

  static Function(String copied)? _onClipboardData;

  static void init({
    Function(String copied)? onClipboardData
  }){
    if(!_hasInit){
      _hasInit = true;
      _onClipboardData = onClipboardData;
      WidgetsBinding.instance.addObserver(ClipboardUtil._instance);
      _clipboardManager = ClipboardManager(clipboardChanged: _onClipboardChanged);
      _clipboardManager.start();
    }
  }

  static void _onClipboardChanged(){
    Log.log('_onClipboardChanged $_hasChanged');
    if(!_hasChanged){
      _hasChanged = true;
    }
  }

  static void close(){
    WidgetsBinding.instance.removeObserver(ClipboardUtil._instance);
    _clipboardManager.stop();
  }

  int _id = 0;
  CancelableOperation? _cancelableOperation;
  void _getClipboardData(){
    _cancelableOperation?.cancel();
    _id = DateTime.now().millisecondsSinceEpoch;
    Log.log('_getClipboardData $_id');
    _cancelableOperation = CancelableOperation.fromFuture(
      Clipboard.getData(Clipboard.kTextPlain),
      onCancel: (){
        Log.log('_getClipboardData $_id canceled');
      }
    ).then((res) {
      if(res != null){
        if(res.text != null){
          _onClipboardData?.call(res.text!);
        }
      }
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch(state){
      case AppLifecycleState.resumed:
        Log.log('onResumed');
        if(_hasChanged){
          _hasChanged = false;
          _getClipboardData();
        }
        break;
      case AppLifecycleState.paused:
        break;
      case AppLifecycleState.hidden:
        break;
      case AppLifecycleState.detached:
        break;
      case AppLifecycleState.inactive:
        break;
    }
  }

}
